package todo_plan

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"tao-admin/configs"
	"tao-admin/internal/model"
)

type PlanCalendarManager struct{}

type SearchPlanCalendarCondition struct {
	Id        *int64  `json:"id"`
	Content   *string `json:"content"`
	StartTime *string `json:"startTime"`
	EndTime   *string `json:"endTime"`
	Ctime     *int64  `json:"ctime"`
	Mtime     *int64  `json:"mtime"`
}

func (manager *PlanCalendarManager) SearchPlanCalendarByConditionMng(ctx *gin.Context, condition *SearchPlanCalendarCondition) ([]model.ToDoCalendarTab, int64, error) {
	page, _ := strconv.Atoi(ctx.Query("page"))
	count, _ := strconv.Atoi(ctx.Query("perPage"))

	db := configs.GetGormDB()
	list := make([]model.ToDoCalendarTab, 0)
	var total int64 = 0

	if condition.Content != nil {
		db = db.Where("content=?", condition.Content)
	}
	if condition.StartTime != nil {
		db = db.Where("startTime=?", condition.StartTime)
	}
	if condition.EndTime != nil {
		db = db.Where("endTime=?", condition.EndTime)
	}
	if condition.Ctime != nil {
		db = db.Where("ctime=?", condition.Ctime)
	}
	if condition.Mtime != nil {
		db = db.Where("mtime=?", condition.Mtime)
	}

	err1 := db.Model(&model.ToDoCalendarTab{}).Count(&total).Error
	if page > 0 && count > 0 {
		db = db.Limit(count).Offset((page - 1) * count)
	}

	db = db.Order("id DESC")

	err2 := db.Find(&list).Error
	if err1 != nil || err2 != nil {
		return nil, 0, nil
	}

	return list, total, nil
}

func (manager *PlanCalendarManager) CreatePlanCalendarMng(ctx *gin.Context, item model.ToDoCalendarTab) error {
	db := configs.GetGormDB()
	err := db.Create(&item).Error
	if err != nil {
		return err
	}
	return nil
}

func (manager *PlanCalendarManager) UpdatePlanCalendarMng(ctx *gin.Context, item model.ToDoCalendarTab) error {
	db := configs.GetGormDB()
	// 先赋值
	updateData := model.ToDoCalendarTab{
		Content:   item.Content,
		StartTime: item.StartTime,
		EndTime:   item.EndTime,
		Ctime:     item.Ctime,
		Mtime:     item.Mtime,
	}

	id := item.Id
	// 查询记录
	if err := db.Where("id = ?", id).First(&item).Error; err != nil {
		return err
	}

	err := db.Model(&item).Where("id = ?", id).Update(updateData).Error
	if err != nil {
		return err
	}
	return nil
}

func (manager *PlanCalendarManager) DeletePlanCalendarMng(ctx *gin.Context, item model.ToDoCalendarTab) error {
	db := configs.GetGormDB()
	id := item.Id
	// 查询记录
	if err := db.Where("id = ?", id).First(&item).Error; err != nil {
		return err
	}
	err := db.Delete(&item).Error
	if err != nil {
		return err
	}
	return nil
}
